import { Component } from '@angular/core';
import {
  NavController,
  LoadingController,
  AlertController,
  Platform
} from 'ionic-angular';
import { HomePage } from '../home/home';
import { Storage } from '@ionic/storage';
import { HttpService } from '../../providers/http.service';
import { GlobalVars } from '../../providers/globalVars';
import { appConfig } from '../../providers/config';
import { CommonFunc } from '../../providers/commonFunc';
import { Camera, CameraOptions, Direction } from '@ionic-native/camera';

import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { SetPage } from '../set/set';
import { AppVersion } from '@ionic-native/app-version';

/*import VConsole from 'vconsole'
const  vConsole = new VConsole();*/

@Component({
  templateUrl: 'login.html',
  providers: [HttpService, CommonFunc]
})
export class LoginPage {
  private loginName = '';
  private password = '';
  private platformName: any;
  private registrationID: any;
  private backButtonPressed = false;
  private faceButton = false;
  version: any;
  remeberPwd: any = false;
  updateFlag: any;
  iosurl: any;
  androidurl: any;
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private alert: AlertController,
    private globalVars: GlobalVars,
    private loading: LoadingController,
    public platform: Platform,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private file: File,
    private camera: Camera,
    private appVersion: AppVersion
  ) {
    this.storage.get("ip").then(ip => {
      if (!ip) {
        window.alert('请设置服务器');
        return;
      }
      this.storage.get("port").then(port => {
        if (ip == 'www.hyjckj.net') {
          appConfig.IP_URL = "https://" + ip + ":" + port + "/";
          appConfig.PREVIEW_URL = "http://" + ip + ":8080/upload/";
        } else if (ip == 'localhost' || ip == '127.0.0.1' || ip == '192.168.43.155') {
          appConfig.IP_URL = "http://localhost:8099/";
          /*appConfig.PREVIEW_URL = "http://www.hyjckj.net:8668/upload/";*/
          appConfig.PREVIEW_URL = "http://www.hyjckj.net:8080/upload/";
          appConfig.APK_DOWNLOAD = 'http://yhtscjg.hyjckj.net:8668/upload/app/elevator.apk';
        } else if (ip == 'wzscjg.hyjckj.net') {
          appConfig.IP_URL = "https://" + ip + ":" + port + "/";
          appConfig.PREVIEW_URL = "http://" + ip + ":8668/upload/";
          appConfig.APK_DOWNLOAD = 'http://yhtscjg.hyjckj.net:8668/upload/app/wzelevator.apk';
        } else if (ip == 'dtwzh.szqts.gov.cn') {
          // 市局地址
          appConfig.IP_URL = "https://" + ip + ":" + port + "/";
          appConfig.PREVIEW_URL = "http://58.210.227.48:8066/upload/";
          appConfig.APK_DOWNLOAD = 'http://58.210.227.48:8066/upload/app/elevator.apk';
        } else {
          appConfig.IP_URL = "https://" + ip + ":" + port + "/";
          // appConfig.IP_URL = "http://172.20.10.4:8099/";
          appConfig.PREVIEW_URL = "http://" + ip + ":8668/upload/";
        }
      });
    });

    this.storage.get('remeberPwd').then(re => {
      if (re) {
        this.remeberPwd = re;
        this.storage.get('hyjgkjp').then(pd => {
          this.password = pd;
        });
      }
    });

    if (this.platform.is('ios')) {
      this.platformName = '0';
    } else if (this.platform.is('android')) {
      this.platformName = '2';
    }

    this.appVersion.getVersionNumber().then(version => {
      this.version = version;
      if (version.toString().indexOf('.') > 0) {
        let version2 = version.toString().replace('.', '0').replace('.', '0');
        this.version = version2;
      }
    });

    try {
      // this.alert.create({
      //   title: '提醒',
      //   message: 'id1是: + ',
      //   buttons: ['确认'],
      //   enableBackdropDismiss: true
      // }).present();
      (<any>window).JPush.getRegistrationID(id => {
        if (id != null && ((id + '').trim()) != '') {
          this.registrationID = id;
          this.storage.set('registrationID', id);
        } else {
          setTimeout(() => {
            (<any>window).JPush.getRegistrationID(id => {
              this.registrationID = id;
              this.storage.set('registrationID', id);
            })
          }, 2000);
        }

      });
    } catch (e) {
      try {
        //异常重试
        setTimeout(function () {
          try {
            (<any>window).JPush.getRegistrationID(id => {
              this.registrationID = id;
              this.storage.set('registrationID', id);
            });
          } catch (e) {
          }
        }, 2000);
      } catch (e) {

      }
    }
    this.platform.registerBackButtonAction(() => {
      //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
      let activeVC = this.navCtrl.getActive().name;
      if (activeVC == 'HomePage') {
        this.showExit();
      } else {
        this.navCtrl.canGoBack() == true ? this.navCtrl.pop() : this.showExit();
      }
    }, 1);
  }

  ionViewDidEnter() {
    this.httpService.getVersion({ version: this.version }).subscribe(data => {
      if (data.status == 200) {
        this.iosurl = data.data.iosurl;
        this.androidurl = data.data.androidurl;
        if (data.data.updateFlag == '2') {
          let aler = this.alert.create({
            title: '升级',
            subTitle: '发现新版本,是否立即升级？',
            enableBackdropDismiss: false,
            buttons: [
              {
                text: '取消',
                handler: () => {
                }
              },
              {
                text: '确定',
                handler: () => {
                  if (this.platformName == '0') {
                    this.commonFunc.toappstore(this.iosurl)
                  }
                  if (this.platformName == '2') {
                    this.httpService.downloadApp(this.androidurl);
                  }
                }
              }
            ]
          });
          aler.present();
        }

        if (data.data.updateFlag == '3') {
          this.updateFlag = "3";
          let aler = this.alert.create({
            title: '升级',
            subTitle: '发现新版本,请立即升级',
            enableBackdropDismiss: false,
            buttons: [
              {
                text: '确定',
                handler: () => {
                  if (this.platformName == '0') {
                    // this.commonFunc.toappstore("itms-apps://itunes.apple.com/cn/app/%E7%94%B5%E6%A2%AF%E5%8A%A8%E6%80%81%E7%9B%91%E7%AE%A1/id1412478466?mt=8")
                    this.commonFunc.toappstore(this.iosurl)

                  }
                  if (this.platformName == '2') {
                    this.httpService.downloadApp(this.androidurl);
                  }

                }
              }
            ]
          });
          aler.present();
        }
      }
    });

  }

  //双击退出提示框
  showExit() {
    if (this.backButtonPressed) {
      //当触发标志为true时，即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      let toas = this.commonFunc.showToast({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'top'
      });
      toas.present();
      this.backButtonPressed = true;
      setTimeout(() => (this.backButtonPressed = false), 2000); //2秒内没有再次点击返回则将触发标志标记为false
    }
  }
  doChose(num) {
    this.navCtrl.push(HomePage, { isPassenger: true });
  }

  //登录
  doSubmit() {
    console.log("dd")
    //注册监听消息通知
    if (this.updateFlag == "3") {
      this.alert.create({
        title: '提醒',
        message: '必须更新App',
        enableBackdropDismiss: false,
        buttons: [
          {
            text: '确定',
            handler: () => {
              if (this.platformName == '0') {
                this.commonFunc.toappstore(this.iosurl);
              }
              if (this.platformName == '2') {
                this.httpService.downloadApp(this.androidurl);
              }

            }
          }
        ]
      }).present();
      return;
    }
    document.addEventListener("jpush.receiveNotification", event => {
      let alerttitad = '1111';
      let alerttitios = '1111';
      alerttitad = (<any>event).alert;
      if ((<any>event).aps) {
        alerttitios = (<any>event).aps.alert;
      }
      if (alerttitad == '您已经在别的设备登录') {
        this.alert.create({
          title: '提醒',
          message: '您的账号在别处登录了，强制下线',
          buttons: ['确认'],
          enableBackdropDismiss: true
        }).present();
        this.storage.set('hyjgkjp', '');
        this.navCtrl.setRoot(LoginPage);
      }
      if (alerttitios == '被踢了') {
        this.alert.create({
          title: '提醒',
          message: '您的账号在别处登录了，强制下线',
          buttons: ['确认'],
          enableBackdropDismiss: true
        }).present();
        this.storage.set('hyjgkjp', '');
        this.navCtrl.setRoot(LoginPage);
      }
    }, false);

    let load = this.loading.create({
      spinner: appConfig.spinner,
      duration: 4000,
      enableBackdropDismiss: true
    });
    if (!this.loginName) {
      this.alert
        .create({
          title: '错误',
          message: '请输入用户名',
          buttons: ['确认'],
          enableBackdropDismiss: true
        })
        .present();
      return;
    }
    if (!this.password) {
      this.alert
        .create({
          title: '错误',
          message: '请输入密码',
          buttons: ['确认'],
          enableBackdropDismiss: true
        })
        .present();
      return;
    }
    let user = {
      userName: this.loginName,
      password: this.password,
      version: this.version
    };
    load.present();
    //this.navCtrl.push(HomePage);
    this.httpService.login(user).subscribe(data => {
      load.dismiss();
      if (data.status == 200) {
        this.storage.set('user', data.data.sysUser);
        this.globalVars.setMyGlobalVar({ token: data.data.token });

        if (data.data.sysUser.partyType != 4) {
          //监管不发通知，不绑定了就
          //用户设备号绑定
          this.storage.get('registrationID').then(registrationID => {
            let jiguangInfo = {
              userId: data.data.sysUser.id,
              registerId: registrationID
            };
            let ob = this.httpService.handleUserRegId(jiguangInfo);
            ob.subscribe(data => {
              console.log(data);
            });
          });
        }
        if (this.remeberPwd) {
          this.storage.set('remeberPwd', this.remeberPwd);
          this.storage.set('hyjgkjp', this.password);
        } else {
          this.storage.set('remeberPwd', this.remeberPwd);
          this.storage.set('hyjgkjp', '');
        }

        this.navCtrl
          .push(HomePage, {
            isPassenger: false,
            id: data.data.sysUser.id,
            partyId: data.data.sysUser.partyId
          })
          .then(() => {
            this.navCtrl
              .getActive()
              .getNav()
              .remove(0);
            //场景埋点
            if (data.data && data.data.status == 1) {
              this.storage.get(data.data.ext2 + data.data.sysUser.id).then(dt => {
                let shownum: number = 0;
                if (dt) {
                  shownum = dt.shownum;
                }

                if (data.data.eventAction == 1) { //nothing to do

                }
                if (data.data.eventAction == 2) {
                  if (data.data.ext1 > shownum) {
                    let totst = this.commonFunc.showToast({
                      message: "恭喜您获得：" + data.data.thing + " 分",
                      duration: 3000,
                      position: "top"
                    });
                    totst.present();
                    this.storage.set(data.data.ext2 + data.data.sysUser.id, { shownum: ++shownum });
                  }

                }
                if (data.data.eventAction == 3) {
                  if (data.data.ext1 > shownum) {
                    this.commonFunc.openUrl(data.data.thing);
                    this.storage.set(data.data.ext2 + data.data.sysUser.id, { shownum: ++shownum });
                  }
                }
                if (data.data.eventAction == 4) {
                  if (data.data.ext1 > shownum) {
                    this.navCtrl.push(data.data.thing, {
                      themeData: data.data
                    });
                  }
                }
              }, error => {

              })
            }
          });
      } else {
        this.alert
          .create({
            title: '错误',
            message: data.message,
            buttons: ['确认'],
            enableBackdropDismiss: true
          })
          .present();
      }
    }, err => {
      load.dismiss();
      let totst = this.commonFunc.showToast({
        message: "服务异常,请检查服务器设置",
        duration: 3000,
        position: "top"
      });
      totst.present();
    });
  }
  reUrl() { }

  getPicture() {
    let options: CameraOptions = {
      quality: 85,
      targetWidth: 200,
      targetHeight: 200,
      cameraDirection: 1
    };
    this.camera
      .getPicture(options)
      .then(imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.checkFace);
        options.fileKey = 'file';
        options.fileName = 'test.jpg';
        options.mimeType = 'image/jpeg';
        options.params = { userCode: this.loginName };
        const fileTransfer = this.transfer.create();
        let load1 = this.loading.create({
          spinner: appConfig.spinner,
          duration: appConfig.timeout
        });
        load1.present();
        fileTransfer.upload(imageData, serverUrl, options).then(data => {
          load1.dismiss();
          if (JSON.parse(data.response)['status'] + '' == '200') {
            this.storage.set('user', JSON.parse(data.response)['data'].sysUser);
            this.globalVars.setMyGlobalVar({
              token: JSON.parse(data.response)['data'].token
            });

            //用户设备号绑定
            this.storage.get('registrationID').then(registrationID => {
              let jiguangInfo = {
                userId: JSON.parse(data.response)['data'].sysUser.id,
                registerId: registrationID
              };
              let ob = this.httpService.handleUserRegId(jiguangInfo);
              ob.subscribe(data => {
                console.log(data);
              });
            });

            this.navCtrl
              .push(HomePage, {
                isPassenger: false,
                id: JSON.parse(data.response)['data'].sysUser.id,
                partyId: JSON.parse(data.response)['data'].sysUser.partyId
              })
              .then(() => {
                this.navCtrl
                  .getActive()
                  .getNav()
                  .remove(0);
              });
          } else {
            this.alert
              .create({
                title: '错误',
                message: JSON.parse(data.response)['message'],
                buttons: ['确认'],
                enableBackdropDismiss: true
              })
              .present();
          }
        }, error => {
          alert(JSON.stringify(error))
        });
      })
      .catch(e => { });
  }

  //判断是否登陆过
  ionViewWillEnter() {
    this.storage.get('user').then(val => {
      if (val['userCode']) {
        this.faceButton = true;
        this.loginName = val['userCode'];
      }
    });
  }

  toSet() {
    this.navCtrl.push(SetPage);
  }
}
